/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Random;

/**
 * <p>Project: javase - ImgUtils
 * <p>Powered by webrx On 2021-12-17 19:35:25
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class ImgUtils {
    private String imgpath;
    private BufferedImage src;
    private Graphics2D g;
    private int sw;
    private int sh;

    public ImgUtils() {

    }

    public ImgUtils(String imgpath) {
        this.imgpath = imgpath;
        try {
            src = ImageIO.read(new File(imgpath));
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init() {
        sw = src.getWidth();
        sh = src.getHeight();
        g = src.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);

    }

    /**
     * resources/font/logo.png
     *
     * @param logosrc
     * @return
     */
    public BufferedImage getLogo(String logosrc) {
        BufferedImage logo = null;
        try {
            logo = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream(logosrc));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return logo;
        }
    }

    public void logo(String logo, int pos, boolean over) {
        var logoimg = getLogo(logo);
        int lw = logoimg.getWidth();
        int lh = logoimg.getHeight();
        int x = 10;
        int y = 10;
        switch (pos) {
            case 1:
                x = 10;
                y = 10;
                break;
            case 2:

                break;
            case 5:
                x = (sw - lw) / 2;
                y = (sh - lh) / 2;
                break;

            case 9:
                x = sw - lw - 10;
                y = sh - lh - 10;
                break;
            default:
                Random rand = new Random();
                x = rand.nextInt(sw - lw - 10) + 10;
                y = rand.nextInt(sh - lh - 10) + 10;
                break;
        }
        g.drawImage(logoimg, x, y, null);
        //用于保存处理后的图片
        g.dispose();
        save(over, "_logo");
    }


    /**
     * 验证码图片效果
     *
     * @return
     */
    public void checkcode(int w, int h, int len, int type) {
        this.src = new BufferedImage(w, h, 2);
        init();
        g.fillRect(0, 0, w, h);
        StringBuffer sbu = new StringBuffer();
        switch (type) {
            case 1:
                sbu.append("0123456789");
                break;
            case 2:
                break;
            case 3:
                break;
            default:
                sbu.append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
                break;
        }
        Random rand = new Random();
        int x = 0;
        int y = 0;
        for (int n = 0; n < len; n++) {
            x = n * 35 + 10;
            y = 22;
            g.setFont(getFont("fonts/et1.ttf", Font.BOLD, 28));
            g.setColor(getColor("rand", 255));
            String str = String.valueOf(sbu.charAt(rand.nextInt(sbu.length() - 1)));
            g.drawString(str, x, y);
        }

        for (int n = 0; n < 50; n++) {
            x = rand.nextInt(w);
            y = rand.nextInt(h);
            g.setFont(getFont("fonts/et1.ttf", Font.BOLD, rand.nextInt(13) + 12));
            g.setColor(getColor("rand", rand.nextInt(50) + 50));
            String str = String.valueOf(sbu.charAt(rand.nextInt(sbu.length() - 1)));
            g.drawString(str, x, y);
        }
    }

    public void text(String text, String font, int fontsize, String color, int pos, boolean over) {
        Font ft = getFont(font, Font.BOLD, fontsize);
        g.setFont(ft);
        g.setColor(getColor(color, 160));


        FontMetrics metrics = g.getFontMetrics(ft);
        int th = metrics.getHeight();
        int tw = metrics.stringWidth(text);

        int padding = 10;
        int x = padding;
        int y = padding;
        switch (pos) {
            case 1:
                x = padding;
                y = padding + th;
                break;
            case 2:
                x = (int) ((sw - tw) / 2);
                y = padding + th;
                break;
            case 3:
                x = sw - tw - padding;
                y = padding + th;
                break;
            case 4:
                x = padding;
                y = (int) ((sh - th) / 2);
                break;
            case 5:
                x = (int) ((sw - tw) / 2);
                y = (int) ((sh - th) / 2);
                break;
            case 6:
                x = sw - tw - padding;
                y = (int) ((sh - th) / 2);
                break;
            case 7:
                x = padding;
                y = sh - padding;
                break;
            case 8:
                x = (int) ((sw - tw) / 2);
                y = sh - padding;
                break;
            case 9:
                x = sw - tw - padding;
                y = sh - padding;
                break;
            default:
                Random r = new Random();
                x = r.nextInt(sw - tw - padding - padding) + padding;
                y = r.nextInt(sh - padding - padding - th) + (padding + th);
                break;
        }

        g.drawString(text, x, y);
        //user.jpg   user_text

        save(over, "_text");

    }

    public void save(String imgpath) {
        this.imgpath = imgpath;
        try {
            ImageIO.write(src, "png", new File("c:/xyz.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void save(boolean over, String extt) {
        this.imgpath = over ? this.imgpath : this.imgpath.replace(".jpg", extt + ".jpg");
        try {
            ImageIO.write(src, "jpg", new File(imgpath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 功能：根据文件TTF文件，建立Font对象
     * url = fonts/xx.ttf
     * url = c:/yy.ttf
     *
     * @param url
     * @param style
     * @param size
     * @return
     */
    public static Font getFont(String url, int style, int size) {
        var is = Thread.currentThread().getContextClassLoader().getResourceAsStream(url);
        Font font = new Font("", style, size);
        try {
            font = Font.createFont(0, is).deriveFont(Font.BOLD, (float) size);
        } catch (Exception e) {
        }
        return font;
    }

    public static Color getRandomColor() {
        return getRandomColor(false);
    }

    public static Color getColor(String color, int alpha) {
        Color c = Color.WHITE;
        switch (color) {
            case "red":
                c = new Color(0xff, 0x00, 0, alpha);
                break;
            case "black":
                c = new Color(0, 0, 0, alpha);
                break;
            case "white":
                c = new Color(255, 255, 255, alpha);
                break;
            default:
                c = getRandomColor(alpha);
        }
        return c;

    }

    /**
     * @param alpha
     * @return
     */
    public static Color getRandomColor(int alpha) {
        Random rand = new Random();
        Color c = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), rand.nextInt(alpha));
        return c;
    }

    public static Color getRandomColor(boolean alpha) {
        Random rand = new Random();
        Color c = null;
        if (alpha) {
            c = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
        } else {
            c = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
        }
        return c;
    }
}
